package groupb6.shopsystem.messaging.server;

import com.fasterxml.jackson.databind.ObjectMapper;
import groupb6.shopsystem.messaging.entity.Notice;
import groupb6.shopsystem.messaging.entity.WebSocketGroup;
import lombok.Getter;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WebsocketServer {
    private static final ObjectMapper jsonParser = new ObjectMapper();

    //分组WS连接池
    @Getter
    private static final Map<String, WebSocketGroup> chattingMap = new ConcurrentHashMap<>();
    //全局WS连接池
    @Getter
    private static final Map<Integer, Session> globalNoticeMap = new ConcurrentHashMap<>();

    //消息缓存,<接收id,发送idList>
    @Getter
    private static final Map<Integer, List<Integer>> messageCache = new ConcurrentHashMap<>();
    public static void addNotice(Notice notice, Integer userId) {
        try {
            //这里的userId为接收者的id
            //如果目标用户已经在线
            List<Notice> noticeList=new ArrayList<>();
            noticeList.add(notice);
            String json = jsonParser.writeValueAsString(noticeList);
            System.out.println(json);
            if(WebsocketServer.getGlobalNoticeMap().containsKey(userId)){
                WebsocketServer.getGlobalNoticeMap().get(userId).getBasicRemote().sendText(json);
            }else {
                //如果目标用户已不在线，将消息加入缓存中
                if(!messageCache.containsKey(userId)){
                    messageCache.put(userId,new ArrayList<>());
                }
                if(!messageCache.get(userId).contains(notice.getSenderId())){
                    messageCache.get(userId).add(notice.getSenderId());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void sendCachedNotices(List<Notice> notices, Integer userId) {
        try {
            String json = jsonParser.writeValueAsString(notices);
            System.out.println(json);
            if(WebsocketServer.getGlobalNoticeMap().containsKey(userId)){
                WebsocketServer.getGlobalNoticeMap().get(userId).getBasicRemote().sendText(json);
            }else {
                throw new RuntimeException("该用户仍未注册，发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
